﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace UndisposedLogViewer
{
    class LogEntry
    {
        public string ObjectID;
        public string Type;
        public string Stack;
    }

    class LogParser : IDisposable
    {
        StreamReader streamReader;

        internal LogParser(string path)
        {
            streamReader = new StreamReader(path);
        }

        internal IEnumerable<LogEntry> GetEntries()
        {
            while (!streamReader.EndOfStream)
            {
                var entry = CreateEntry(streamReader);
                yield return entry;
                
                //Eat up empty line
                streamReader.ReadLine();
            }
        }

        private LogEntry CreateEntry(StreamReader streamReader)
        {
            return new LogEntry()
            {
                ObjectID = streamReader.ReadLine(),
                Type = streamReader.ReadLine(),
                Stack = ReadUntilEndOfFileOrEmptyLine(streamReader)
            };
        }

        private string ReadUntilEndOfFileOrEmptyLine(StreamReader streamReader)
        {
            StringBuilder builder = new StringBuilder();

            string line = null;

            while ((line = streamReader.ReadLine()) != null)
            {
                if (string.IsNullOrEmpty(line))
                    break;

                builder.AppendLine(line);
            }
            return builder.ToString();
        }

        #region IDisposable Members

        public void Dispose()
        {
            streamReader.Dispose();
        }

        #endregion
    }
}
